//
//  postViewController.m
//  projectAlcohol
//
//  Created by Anand Rao on 11/21/13.
//  Copyright (c) 2013 home. All rights reserved.
//

#import "postViewController.h"

@interface postViewController ()

@end

@implementation postViewController
@synthesize output;
@synthesize x;
@synthesize y;
@synthesize z;
@synthesize url;
@synthesize responseData = _responseData;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    [self.view endEditing:YES];
    self.responseData = [NSMutableData data];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)postDown:(id)sender {
    
    NSString *strURL = [NSString stringWithFormat:@"http://localhost/project-alcohol/index.php/%@",url.text];
    
    NSString *bodyData = [NSString stringWithFormat:@"%@/%@/%@",x.text,y.text,z.text];
    
//    NSData *postData = [strURL dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    
//    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
    
    NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]];
    [postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [postRequest setHTTPMethod:@"POST"];
    [postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
    
    //calling line
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:postRequest delegate:self];
    
    NSLog(@"%@",connection);
    NSLog(@"%@",bodyData);
    
    if (!connection) {
        NSLog(@"Connection Failed");
    }
}

/*
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"didReceiveResponse");
    [self.responseData setLength:0];
}
*/

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"didReceiveData");
    [self.responseData appendData:data];
    output.text = [[NSString alloc] initWithData:self.responseData encoding:NSASCIIStringEncoding];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [z resignFirstResponder];
    return YES;
}
@end
